#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#define BUFFER_SIZE 20

int main() {
    int oldfd1, oldfd2, newfd1, newfd2;
    char buf[BUFFER_SIZE];

    // 打开文件（添加O_CREAT标志自动创建文件）
    oldfd1 = open("a.txt", O_RDWR | O_CREAT, 0644);
    oldfd2 = open("b.txt", O_RDWR | O_CREAT, 0644);

    // 验证文件描述符分配
    printf("The oldfd1 file descriptor = %d\n", oldfd1);  // 预期3
    printf("The oldfd2 file descriptor = %d\n", oldfd2);  // 预期4

    // 执行dup操作
    newfd1 = dup(oldfd1);
    printf("The newfd1 file descriptor = %d\n", newfd1);  // 预期5
    
    // 关闭标准输入（文件描述符0）
    close(0);
    
    // 执行dup2操作
    newfd2 = dup2(oldfd1, 0);  // 将oldfd1复制到0号描述符
    if(newfd2 == -1) {
        perror("dup2 failed");
        exit(EXIT_FAILURE);
    }
    printf("The newfd2 file descriptor = %d\n", newfd2);  // 预期0
    
    // 从新的0号描述符读取数据
    ssize_t bytes_read = read(0, buf, BUFFER_SIZE-1);
    if(bytes_read == -1) {
        perror("read failed");
        exit(EXIT_FAILURE);
    }
    buf[bytes_read] = '\0';
    printf("I have read from a.txt: %s\n", buf);

    // 关闭所有文件描述符
    close(oldfd1);
    close(oldfd2);
    close(newfd1);
    close(newfd2);

    return 0;
}
